import { getToken, getExpiresIn, getTokenTime, clearAuthCache } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
import router from '@/router'

// token刷新阈值（分钟）
const REFRESH_THRESHOLD = 120

// 检查token是否需要刷新
export function shouldRefreshToken() {
  const token = getToken()
  const expiresIn = getExpiresIn()
  const tokenTime = getTokenTime()

  if (!token || !expiresIn || expiresIn === -1) {
    return false
  }

  const currentTime = new Date().getTime()
  const tokenCreateTime = parseInt(tokenTime)
  const expiresInMs = parseInt(expiresIn) * 60 * 1000 // 转换为毫秒
  const timeElapsed = currentTime - tokenCreateTime
  const timeRemaining = expiresInMs - timeElapsed

  // 如果剩余时间少于阈值，需要刷新
  return timeRemaining < (REFRESH_THRESHOLD * 60 * 1000)
}

// 检查token是否已过期
export function isTokenExpired() {
  const token = getToken()
  const expiresIn = getExpiresIn()
  const tokenTime = getTokenTime()

  if (!token || !expiresIn || expiresIn === -1) {
    return true
  }

  const currentTime = new Date().getTime()
  const tokenCreateTime = parseInt(tokenTime)
  const expiresInMs = parseInt(expiresIn) * 60 * 1000
  const timeElapsed = currentTime - tokenCreateTime

  return timeElapsed >= expiresInMs
}

// 自动刷新token
export async function autoRefreshToken() {
  const userStore = useUserStore()

  try {
    // 先检查token是否存在
    const token = getToken()
    if (!token) {
      console.log('Token不存在，跳转登录')
      await userStore.fedLogOut()
      router.push('/login')
      return false
    }

    if (isTokenExpired()) {
      console.log('Token已过期，清除缓存并跳转登录')
      await userStore.fedLogOut()
      router.push('/login')
      return false
    }

    if (shouldRefreshToken()) {
      console.log('Token即将过期，开始刷新')
      await userStore.refreshToken()
      console.log('Token刷新成功')
      return true
    }

    return true
  } catch (error) {
    console.error('Token刷新失败:', error)
    await userStore.fedLogOut()
    router.push('/login')
    return false
  }
}

// 强制清除所有缓存并跳转登录
export function forceLogout() {
  const userStore = useUserStore()
  clearAuthCache()
  userStore.fedLogOut()
  router.push('/login')
}

// 定时检查token状态
let tokenCheckTimer = null

export function startTokenCheck() {
  stopTokenCheck() // 先停止之前的定时器

  tokenCheckTimer = setInterval(() => {
    const token = getToken()
    if (token) {
      autoRefreshToken()
    }
  }, 5 * 60 * 1000) // 每5分钟检查一次
}

export function stopTokenCheck() {
  if (tokenCheckTimer) {
    clearInterval(tokenCheckTimer)
    tokenCheckTimer = null
  }
}

// 页面可见性变化时的处理
export function handleVisibilityChange() {
  if (document.visibilityState === 'visible') {
    // 页面变为可见时，立即检查token状态
    const token = getToken()
    if (token) {
      autoRefreshToken()
    }
  }
}

// 初始化token管理
export function initTokenManager() {
  // 启动定时检查
  startTokenCheck()

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 监听页面刷新/关闭
  window.addEventListener('beforeunload', () => {
    stopTokenCheck()
  })
}

// 清理token管理
export function destroyTokenManager() {
  stopTokenCheck()
  document.removeEventListener('visibilitychange', handleVisibilityChange)
}
